package org.lq.us.web;

import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.lq.us.entity.Users;
import org.lq.us.service.UsersService;
import org.lq.us.service.impl.UsersServiceImpl;

import com.google.gson.Gson;

/**
 * Servlet implementation class PhoneLoginServlet
 */
@WebServlet("/PhoneLoginServlet")
public class PhoneLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static Map<String,Object> map = new HashMap<String,Object>();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PhoneLoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("phoneName");
		String pwd = request.getParameter("phonePwd");
		String uuid = request.getParameter("uuid");
		String userInfo = request.getParameter("userInfo");
		UsersService usersService = new UsersServiceImpl();
		Users user = null;
		
		if(userInfo!=null && !"".equals(userInfo)) {
 			 String userJson = new String(Base64.getDecoder().decode(userInfo));
 			 
			Gson gson = new Gson();
 			Users u = gson.fromJson(userJson, Users.class);
 			name = u.getUserName();
 			pwd = u.getPassword();
 			user =  usersService.login(name, pwd,true);
		}else {
			user =  usersService.login(name, pwd);
		}
		
		
		System.out.println(user+"-----------------------------------");
		
		if(user!=null) {
			map.put(uuid, user);
			request.getSession().setAttribute("user", user);
			String json = new Gson().toJson(user);
			String jmstr = Base64.getEncoder().encodeToString(json.getBytes());
			response.sendRedirect("existence.html?u="+jmstr);
		}else {
			response.sendRedirect("phone.html");
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
